/*
 * @lc app=leetcode.cn id=395 lang=cpp
 *
 * [395] 至少有 K 个重复字符的最长子串
 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
c++
using namespace std;
// @lc code=start
class Solution {
public:
//分治法递归，因为可以把字符串根据小于k的字符分割
    int dfs(const string& s, int l, int r, int k) {
        vector<int> cnt(26, 0);
        //统计字符出现次数
        for (int i = l; i <= r; i++) {
            cnt[s[i] - 'a']++;
        }
        //小于k的字符
        char split = 0;
        for (int i = 0; i < 26; i++) {
            if (cnt[i] > 0 && cnt[i] < k) {
                split = i + 'a';
                break;
            }
        }
        //没有小于k的就返回整个长度
        if (split == 0) {
            return r - l + 1;
        }

        int i = l;
        int ret = 0;
        while (i <= r) {
            //跳过split字符
            while (i <= r && s[i] == split) {
                i++;
            }
            if (i > r) {
                break;
            }
            //大于k的起始点
            int start = i;
            //计算r
            while (i <= r && s[i] != split) {
                i++;
            }

            int length = dfs(s, start, i - 1, k);
            ret = max(ret, length);
        }
        return ret;
    }

    int longestSubstring(string s, int k) {
        int n = s.length();
        return dfs(s, 0, n - 1, k);
    }
};

// @lc code=end

